import Message from "../../../miniprogram_npm/tdesign-miniprogram/message/index";
import { CardCategory, CardCategoryMap, EnergyType, EnergyTypeMap, TriggerColorStrMap, TriggerStrMap, TriggerType, TriggerTypeLogoMap, TriggerTypeMap, UaCard, UaCardSearchRequest } from "../../../models/ua-card.model";
import { GlobalService } from "../../../services/global.service";
import { UaCardService } from "../../../services/ua-card.service";

// pages/user/deck-card-search/deck-card-search.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FILE_HOST: GlobalService.FILE_HOST,
    STATIC_ASSETS_HOST: GlobalService.STATIC_ASSETS_HOST,
    cardList: [] as UaCard[],
    idCountMap: {} as { [key: number]: number },
    fab: {
      theme: 'danger',
      size: 'small'
    },
    defaultSearchRequest: {
      needEnergyCountMin: 0,
      needEnergyCountMax: 15,
      needEnergyType: undefined,
      bpMax: 10000,
      bpMin: 0,
      generateEnergyCountMax: 3,
      generateEnergyCountMin: 0,
      generateEnergyType: undefined,
      needApMin: 1,
      needApMax: 2,
      cardCategory: undefined,
      triggerType: undefined,
      attribute: undefined,
      packNo: undefined,
    } as UaCardSearchRequest,
    hasMore: true,
    display: true,
    attributes: '',
    packNos: '',
    needEnergyCountMax: 0,
    bpMax: 0,
    generateEnergyCountMax: 3,
    gridMode: true,
    TriggerTypeLogoMap: TriggerTypeLogoMap,
    TriggerStrMap: TriggerStrMap,
    TriggerColorStrMap: TriggerColorStrMap,
    CardCategoryMap: CardCategoryMap,
    CardCategory: CardCategory,
    cardCategory: '',
    detailVisible: false,
    fullPreview: false,
    detailCard: {} as UaCard,
    // 显示用
    categoryCountMap: {} as { [key: string]: number },
    characterList: [] as UaCard[],
    eventList: [] as UaCard[],
    fieldList: [] as UaCard[],
  },

  customData: {
    cardList: [] as UaCard[],
    filteredList: [] as UaCard[],
    idCountMap: {} as { [key: number]: number },
    cardDeckNoCountMap: {} as { [key: string]: number },
    colorCount: 0,
    finalCount: 0,
    specialCount: 0,
    needEnergyCountMax: 0,
    bpMax: 0,
    generateEnergyCountMax: 3,
    init: false,
    searchRequest: {} as UaCardSearchRequest,
    currentPage: 0,
    size: 24,
    totalPage: 0,
    ipId: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    wx.setNavigationBarTitle({
      title: '卡牌查找'
    });
    this.customData.idCountMap = JSON.parse(JSON.stringify(GlobalService.ID_COUNT_MAP));
    this.customData.cardDeckNoCountMap = JSON.parse(JSON.stringify(GlobalService.DECKNO_COUNT_MAP));
    this.customData.ipId = options.ipId;
    this.setData({
      idCountMap: this.customData.idCountMap,
      display: !!options.display
    });
    UaCardService.findListByIpId(options.ipId).then((response: UaCard[]) => {
      const deckNos: string[] = [];
      const attributeSet = new Set<string>();
      const packNoSet = new Set<string>();
      for (const card of response) {
        if (!!this.customData.cardDeckNoCountMap[card.cardDeckNo!] && !deckNos.includes(card.cardDeckNo!)) {
          deckNos.push(card.cardDeckNo!);
          if (card.triggerType === TriggerType.Color) {
            this.customData.colorCount += this.customData.cardDeckNoCountMap[card.cardDeckNo!];
          }
          if (card.triggerType === TriggerType.Special) {
            this.customData.specialCount += this.customData.cardDeckNoCountMap[card.cardDeckNo!];
          }
          if (card.triggerType === TriggerType.Final) {
            this.customData.finalCount += this.customData.cardDeckNoCountMap[card.cardDeckNo!];
          }
        }
        if (!!card.needEnergyCount && this.customData.needEnergyCountMax < card.needEnergyCount) {
          this.customData.needEnergyCountMax = card.needEnergyCount;
        }
        if (!!card.bp && this.customData.bpMax < card.bp) {
          this.customData.bpMax = card.bp;
        }
        // if (!!card.generateEnergyCount && this.customData.generateEnergyCountMax < card.generateEnergyCount) {
        //   this.customData.generateEnergyCountMax = card.generateEnergyCount;
        // }
        for (const attr of card.attribute ?? []) {
          attributeSet.add(attr);
        }
        packNoSet.add(card.packNo!);
      }

      let defaultSearchRequest = JSON.parse(JSON.stringify(GlobalService.DEFAULT_SEARCH_REQ));
      if (this.data.display || !this.data.display && JSON.stringify(GlobalService.DEFAULT_SEARCH_REQ) === "{}") {
        defaultSearchRequest = {
          needEnergyCountMin: 0,
          needEnergyCountMax: 0,
          needEnergyType: undefined,
          bpMax: 0,
          bpMin: 0,
          generateEnergyCountMax: 3,
          generateEnergyCountMin: 0,
          generateEnergyType: undefined,
          needApMin: 1,
          needApMax: 2,
          cardCategory: undefined,
          triggerType: undefined,
          attribute: '',
          packNo: ''
        } as UaCardSearchRequest;
        defaultSearchRequest.needEnergyCountMax = this.customData.needEnergyCountMax;
        defaultSearchRequest.bpMax = this.customData.bpMax;
        defaultSearchRequest.generateEnergyCountMax = this.customData.generateEnergyCountMax;
      }
      if (!!options.mainEnergyType) {
        defaultSearchRequest.needEnergyType = options.mainEnergyType;
        this.setData({
          needEnergyText: EnergyTypeMap[options.mainEnergyType as EnergyType]
        })
      }
      this.customData.cardList = response;
      this.customData.filteredList = JSON.parse(JSON.stringify(response));
      this.customData.totalPage = Math.ceil(this.customData.filteredList.length / this.customData.size);
      const attributes = [...attributeSet];
      const packNos = [...packNoSet];
      this.setData({
        cardList: JSON.parse(JSON.stringify(this.customData.filteredList.slice(0, this.customData.size))),
        defaultSearchRequest: JSON.parse(JSON.stringify(defaultSearchRequest)),
        attributes: attributes.length > 0 ? attributes.join(',') : '',
        packNos: packNos.length > 0 ? packNos.join(',') : '',
        needEnergyCountMax: this.customData.needEnergyCountMax,
        bpMax: this.customData.bpMax,
        generateEnergyCountMax: this.customData.generateEnergyCountMax,
      });

      this.refreshInfo();

    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (!this.data.display) {
      GlobalService.ID_COUNT_MAP = JSON.parse(JSON.stringify(this.customData.idCountMap));
      GlobalService.DECKNO_COUNT_MAP = JSON.parse(JSON.stringify(this.customData.cardDeckNoCountMap));
      GlobalService.DEFAULT_SEARCH_REQ = JSON.parse(JSON.stringify(this.customData.searchRequest));
    } else {
      GlobalService.clearCurrentEditingDeckInfo();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.onLoadMore();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onSearch(e: any) {
    this.customData.searchRequest = e.detail;
    this.filter();
    this.onRefresh();
  },

  onRefresh() {
    this.customData.currentPage = 0;
    this.cutlist();
  },

  onLoadMore() {
    if (!this.data.hasMore) {
      return;
    }
    this.customData.currentPage++;
    this.cutlist();
  },

  onReset(e: any) {
    this.customData.searchRequest = e.detail;
  },

  filter() {
    console.log(this.customData.searchRequest);
    const filterd: UaCard[] = []
    for (const item of this.customData.cardList) {
      if (!!item.bp) {
        if (this.customData.searchRequest.bpMin! > item.bp! || item.bp! > this.customData.searchRequest.bpMax!) {
          continue;
        }
      } else {
        if (this.customData.searchRequest.bpMin! !== 0) {
          continue;
        }
      }

      if (!!item.needAp) {
        if (this.customData.searchRequest.needApMin! > item.needAp! || item.needAp! > this.customData.searchRequest.needApMax!) {
          continue;
        }
      } else {
        if (this.customData.searchRequest.needApMin! !== 0) {
          continue;
        }
      }

      if (!!item.needEnergyCount) {
        if (this.customData.searchRequest.needEnergyCountMin! > item.needEnergyCount! || item.needEnergyCount! > this.customData.searchRequest.needEnergyCountMax!) {
          continue;
        }
      } else {
        if (this.customData.searchRequest.needEnergyCountMin! !== 0) {
          continue;
        }
      }

      if (!!item.generateEnergyCount) {
        if (this.customData.searchRequest.generateEnergyCountMin! > item.generateEnergyCount! || item.generateEnergyCount! > this.customData.searchRequest.generateEnergyCountMax!) {
          continue;
        }
      } else {
        if (this.customData.searchRequest.generateEnergyCountMin! !== 0) {
          continue;
        }
      }

      if (!!this.customData.searchRequest.cardCategory && item.cardCategory !== this.customData.searchRequest.cardCategory) {
        continue;
      }

      if (!!this.customData.searchRequest.generateEnergyType && item.generateEnergyType !== this.customData.searchRequest.generateEnergyType) {
        continue;
      }

      if (!!this.customData.searchRequest.needEnergyType && item.needEnergyType !== this.customData.searchRequest.needEnergyType) {
        continue;
      }

      if (!!this.customData.searchRequest.triggerType && item.triggerType !== this.customData.searchRequest.triggerType) {
        continue;
      }

      if (!!this.customData.searchRequest.attribute && (!item.attribute || item.attribute.indexOf(this.customData.searchRequest.attribute) === -1)) {
        continue;
      }

      if (!!this.customData.searchRequest.packNo && (!item.packNo || item.packNo.indexOf(this.customData.searchRequest.packNo) === -1)) {
        continue;
      }

      if (!!this.customData.searchRequest.rare && (!item.rare || item.rare !== this.customData.searchRequest.rare)) {
        continue;
      }

      filterd.push(item);
    }
    this.customData.filteredList = filterd;
    this.customData.totalPage = Math.ceil(filterd.length / this.customData.size);
  },

  cutlist() {
    const start = this.customData.currentPage * this.customData.size;
    const stop = start + this.customData.size;
    this.setData({
      cardList: JSON.parse(JSON.stringify(this.customData.filteredList.slice(0, stop))),
      hasMore: stop < this.customData.filteredList.length
    })
  },

  changeMode() {
    this.setData({
      gridMode: !this.data.gridMode
    })
  },

  onIncrease(e: any) {
    const id = e.detail;
    const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    if (!card) return;
    const count = this.customData.cardDeckNoCountMap[card.cardDeckNo!] ? +this.customData.cardDeckNoCountMap[card.cardDeckNo!] : 0;
    if (count >= card.limitCount!) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: `「${card.cardName}(${card.cardDeckNo})」最多只能投入${card.limitCount}张`,
      });
      return;
    }
    if (!!card.triggerType) {
      let triggerFull = false;
      switch (card.triggerType) {
        case TriggerType.Color:
          triggerFull = this.customData.colorCount >= 4;
          if (!triggerFull) {
            this.customData.colorCount++;
          }
          break;
        case TriggerType.Final:
          triggerFull = this.customData.finalCount >= 4;
          if (!triggerFull) {
            this.customData.finalCount++;
          }
          break;
        case TriggerType.Special:
          triggerFull = this.customData.specialCount >= 4;
          if (!triggerFull) {
            this.customData.specialCount++;
          }
          break;
      }
      if (triggerFull) {
        Message.warning({
          context: this,
          offset: [20, 32],
          duration: 3000,
          content: `「${TriggerTypeMap[card.triggerType!]}」触发最多只能投入4张`,
        });
        return;
      }
    }
    if (!!card.cardConflict) {
      const conflictList = card.cardConflict.split(',');
      for (const deckNo of conflictList) {
        if (this.customData.cardDeckNoCountMap[deckNo]) {
          Message.warning({
            context: this,
            offset: [20, 32],
            duration: 3000,
            content: `卡组中存在「${deckNo}」，无法投入本卡片。`,
          });
          return;
        }
      }
    }
    if (!this.customData.cardDeckNoCountMap[card.cardDeckNo!]) {
      this.customData.cardDeckNoCountMap[card.cardDeckNo!] = 1;
      this.customData.idCountMap[card.id!] = 1;
      this.setData(
        { idCountMap: this.customData.idCountMap }
      );
    } else {
      this.customData.cardDeckNoCountMap[card.cardDeckNo!]++;
      if (this.customData.idCountMap[card.id!]) {
        this.customData.idCountMap[card.id!]++;
      } else {
        this.customData.idCountMap[card.id!] = 1;
      }
      this.setData(
        { idCountMap: this.customData.idCountMap }
      );
    }
    this.refreshInfo();
  },


  onMax(e: any) {
    const id = e.detail;
    const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    if (!card) return;
    if (!!card.cardConflict) {
      const conflictList = card.cardConflict.split(',');
      for (const deckNo of conflictList) {
        if (this.customData.cardDeckNoCountMap[deckNo]) {
          return;
        }
      }
    }
    const count = this.customData.cardDeckNoCountMap[card.cardDeckNo!] ? +this.customData.cardDeckNoCountMap[card.cardDeckNo!] : 0;
    let triggerLeft = card.triggerType === TriggerType.Color || card.triggerType === TriggerType.Final || card.triggerType === TriggerType.Special ? 4 : Infinity;
    if (!!card.triggerType) {
      switch (card.triggerType) {
        case TriggerType.Color:
          triggerLeft -= this.customData.colorCount - count;
          break;
        case TriggerType.Final:
          triggerLeft -= this.customData.finalCount - count;
          break;
        case TriggerType.Special:
          triggerLeft -= this.customData.specialCount - count;
          break;
      }
    }

    let limit = Math.min(triggerLeft, card.limitCount!);
    if (limit > count) {
      this.customData.cardDeckNoCountMap[card.cardDeckNo!] = limit;
      if (!this.customData.idCountMap[card.id!]) {
        this.customData.idCountMap[card.id!] = limit - count;
      } else {
        this.customData.idCountMap[card.id!] += limit - count;
      }
    }

    if (!!card.triggerType) {
      switch (card.triggerType) {
        case TriggerType.Color:
          this.customData.colorCount += limit - count;
          break;
        case TriggerType.Final:
          this.customData.finalCount += limit - count;
          break;
        case TriggerType.Special:
          this.customData.specialCount += limit - count;
          break;
      }
    }
    this.setData(
      { idCountMap: this.customData.idCountMap }
    );
    this.refreshInfo();
  },

  onDecrease(e: any) {
    const id = e.detail;
    const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    if (!card) return;
    if (!this.customData.idCountMap[card.id!]) {
      return;
    }
    const count = +this.customData.idCountMap[card.id!];
    if (count <= 0) {
      return;
    }
    if (!!card.triggerType) {
      switch (card.triggerType) {
        case TriggerType.Color:
          this.customData.colorCount--;
          if (this.customData.colorCount < 0) {
            this.customData.colorCount = 0;
          }
          break;
        case TriggerType.Final:
          this.customData.finalCount--;
          if (this.customData.finalCount < 0) {
            this.customData.finalCount = 0;
          }
          break;
        case TriggerType.Special:
          this.customData.specialCount--;
          if (this.customData.specialCount < 0) {
            this.customData.specialCount = 0;
          }
          break;
      }
    }
    this.customData.cardDeckNoCountMap[card.cardDeckNo!]--;
    this.customData.idCountMap[card.id!]--;
    this.setData(
      { idCountMap: this.customData.idCountMap }
    );
    this.refreshInfo();
  },

  addDeck() {
    wx.navigateTo({
      url: `/pages/user/user-deck-add/user-deck-add.page?ipId=${this.customData.ipId}`,
    });
  },

  openDetail(e: any) {
    const cardId = e.detail;
    this.detail(cardId);
  },

  showDetail(e: any) {
    const cardId = e.currentTarget.dataset.id;
    this.detail(cardId);
  },

  detail(cardId: number) {
    for (const card of this.customData.cardList) {
      if (card.id === cardId) {
        this.setData({
          detailVisible: true,
          detailCard: card
        });
        break;
      }
    }
  },

  onDetailVisibleChange(e: any) {
    this.setData({
      detailVisible: e.detail.visible,
    });
  },

  onPrev(e: any) {
    const detailCardId = e.detail;
    let p = 0;
    for (let i = 0; i < this.customData.filteredList.length; i++) {
      if (detailCardId === this.customData.filteredList[i].id) {
        p = i;
        break;
      }
    }
    if (p === 0) {
      p = this.customData.filteredList.length - 1;
    } else {
      p--;
    }
    this.setData({
      detailCard: this.customData.filteredList[p]
    })
  },

  onNext(e: any) {
    const detailCardId = e.detail;
    let p = 0;
    for (let i = 0; i < this.customData.filteredList.length; i++) {
      if (detailCardId === this.customData.filteredList[i].id) {
        p = i;
        break;
      }
    }
    if (p === this.customData.filteredList.length - 1) {
      p = 0;
    } else {
      p++;
    }
    this.setData({
      detailCard: this.customData.filteredList[p]
    })
  },

  refreshInfo() {
    const deckNos: string[] = [];
    const characterList: UaCard[] = [];
    const eventList: UaCard[] = [];
    const fieldList: UaCard[] = [];
    const categoryCountMap: { [key: string]: number } = {};
    let total = 0;
    for (const card of this.customData.cardList) {
      if (!!this.customData.cardDeckNoCountMap[card.cardDeckNo!] && !deckNos.includes(card.cardDeckNo!)) {
        deckNos.push(card.cardDeckNo!);
      }
      if (!!this.customData.idCountMap[card.id!]) {
        if (!card.cardImgSm) {
          card.cardImgSm = card.cardImg?.replace('.png', '.jpg');
        }
        switch (card.cardCategory) {
          case CardCategory.Character:
            characterList.push(card);
            break;
          case CardCategory.Event:
            eventList.push(card);
            break;
          case CardCategory.Field:
            fieldList.push(card);
            break;
        }
        if (card.cardCategory) {
          if (!categoryCountMap[card.cardCategory.toString().toLowerCase()]) {
            categoryCountMap[card.cardCategory.toString().toLowerCase()] = 0;
          }
          categoryCountMap[card.cardCategory.toString().toLowerCase()] += this.customData.idCountMap[card.id!];
          total += this.customData.idCountMap[card.id!];
        }
      }
    }
    this.setData({
      characterList,
      eventList,
      fieldList,
      categoryCountMap,
      total
    });
  },

  cardCategoryChange(e: any) {
    console.log(e)
    this.setData({
      cardCategory: e.currentTarget.dataset['category']
    })
  },

  previewFull() {
    this.setData({
      fullPreview: !this.data.fullPreview
    })
  },

  scrollTo(e: any) {
    if (!!this.data.fullPreview) {
      return;
    }
    const id = e.currentTarget.dataset['id'];
    let index = 0;
    let pos = 0;
    for (let i = 0; i < this.customData.filteredList.length; i++) {
      if (`${id}` === `${this.customData.filteredList[i].id}`) {
        index = i;
        pos = !this.data.gridMode ? i : Math.floor(i / 4);
        break;
      }
    }
    if (this.data.cardList.length < index) {
      const end = Math.ceil(index / 24) * 24;
      this.setData({
        cardList: JSON.parse(JSON.stringify(this.customData.filteredList.slice(0, end))),
        hasMore: end < this.customData.filteredList.length
      })
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: (290 * wx.getSystemInfoSync().windowWidth / 750 + 24) * pos
        }).then()
      }, 100);
    } else {
      wx.pageScrollTo({
        scrollTop: (290 * wx.getSystemInfoSync().windowWidth / 750 + 16) * pos
      }).then()
    }
  }
})